<?php

namespace lc\helpers;

class Curl
{
    const ALLOW_HOSTS = [

    ];

    /*
     * @desc    curl请求
     * @param   $url
     * @param   string  $method
     * @param   mixed   $header
     * @param   string  $data
     * @return  bool|mixed
     */
    public static function requestCurl($url, $method = 'GET', $header = [], $data = '')
    {
        $ch = curl_init();

        if (!self::isHostValid($url)) {
            throw new \Exception('Host 非法，请求被拦截');
        }


        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($data) {
                $url = $url . '?' . $data;
            }
            curl_setopt($ch, CURLOPT_URL, $url);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            $errorNo = curl_errno($ch);
            $error   = curl_error($ch);
            throw new \Exception('curl出错，错误码: ' . $errorNo . '，错误信息：' . $error);
        } else {
            curl_close($ch);
            return $result;
        }
    }

    /**
     * @desc 获取IP
     */
    public static function ip()
    {
        $ip = "unknown";
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches[0] : $ip;
    }

    /**
     * @desc    判断 host 是否合法
     * @param   string $url
     * @return  bool
     */
    private static function isHostValid(string $url)
    {
        $parseRes = parse_url($url);
        if (isset($parseRes['host']) && in_array($parseRes['host'], self::ALLOW_HOSTS)) {
            return true;
        } else {
            return false;
        }
    }
}
